package com.qf.controller;

import com.github.pagehelper.PageInfo;
import com.gzk.entity.SealType;
import com.qf.entity.*;
import com.qf.service.*;
import com.qf.utils.ExcelUtils;
import com.qf.utils.NumberUtil;
import com.qf.utils.R;
import com.qf.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@Slf4j
public class AdminController {

    @Resource
    private AdminService adminService;

    @Resource
    private DeptService deptService;

    @Resource
    private ClasssifyService classsifyService;

    @Resource
    private SealTypeService sealTypeService;

    @Resource
    private CarService carService;

    @Resource
    private MeetService meetService;

    @Resource
    private MeetTypeService meetTypeService;

    @Resource
    private ReserveMeetService reserveMeetService;

    @Resource
    private UserService userService;

    @Resource
    private ReserveCarService reserveCarService;

    //印刷名片页面
    @GetMapping("/resource/xingzheng/demo5/list")
    public String cardUi(HttpSession session, Model model){

        //获取存到session里面的user信息
        User user = (User) session.getAttribute("user");
        //根据user里的部门id获取部门信息
        Dept dept=deptService.InfoById(user.getDeptId());
        //根据职位id获取职位信息
        Classsify classsify=classsifyService.InfoById(user.getClasssifyId());

        model.addAttribute("dept",dept);
        model.addAttribute("classsify",classsify);
        model.addAttribute("dated",new Date());
        return "resource/xingzheng/demo5/list";
    }

    //印刷页面
    @PostMapping("/administrative/card")
    @ResponseBody
    public ResultVO card(@Valid Card card, BindingResult bindingResult){

        //校验参数
        if(bindingResult.hasErrors()){
            String msg = bindingResult.getFieldError().getDefaultMessage();
            log.info("【打印名片信息】参数错误，card={},msg={}",card,msg);
            return R.error(199,msg);
        }

        adminService.card(card);

        return R.ok();
    }

    //申请用章页面
    @GetMapping("/resource/xingzheng/demo3/list")
    public String sealUi(HttpSession session, Model model){

        //获取存到session里面的user信息
        User user = (User) session.getAttribute("user");
        //根据user里的部门id获取部门信息
        Dept dept=deptService.InfoById(user.getDeptId());
        //根据职位id获取职位信息
        Classsify classsify=classsifyService.InfoById(user.getClasssifyId());

        //获取全部用章类型
        List<SealType> typeList = sealTypeService.findAll();

        model.addAttribute("dept",dept);
        model.addAttribute("classsify",classsify);
        model.addAttribute("dated",new Date());
        model.addAttribute("list",typeList);
        return "resource/xingzheng/demo3/list";
    }

    //用章申请
    @PostMapping("/administrative/seal")
    @ResponseBody
    public ResultVO seal(@Valid Seal seal, BindingResult bindingResult){

        //校验参数
        if(bindingResult.hasErrors()){
            String msg = bindingResult.getFieldError().getDefaultMessage();
            log.info("【申请用章信息】用章申请失败，seal={},msg={}",seal,msg);
            return R.error(199,msg);
        }

        adminService.insertSeal(seal);

        return R.ok();
    }





    //用车管理页面
    @GetMapping("/resource/xingzheng/demo2/list")
    public String carUi(@RequestParam(defaultValue = "1") Integer page, HttpSession session, Model model){

          Integer size=3;

         //获取全部车型
         PageInfo<Car> pageInfo = carService.findAll(page,size);


        model.addAttribute("pageInfo",pageInfo);
        return "resource/xingzheng/demo2/list";
    }

    //添加车页面
    @GetMapping("/administrative/saveCar-ui")
    public String saveCarUi(){
        return "resource/xingzheng/demo2/add";
    }

    //添加车辆
    @PostMapping("/administrative/saveCar")
    @ResponseBody
    public ResultVO saveCar(@Valid Car car, BindingResult bindingResult){

        //校验参数
        if(bindingResult.hasErrors()){
            String msg = bindingResult.getFieldError().getDefaultMessage();
            log.info("【车辆信息】车辆信息错误，carl={},msg={}",car,msg);
            return R.error(199,msg);
        }
        adminService.insertCar(car);

        return R.ok();
    }

    //修改车辆信息页面
    @GetMapping("/administrative/update-ui")
    public String updateUi(Integer id,Integer page,Model model){

        //根据id查询车辆信息
        Car car=carService.findById(id);
        model.addAttribute("car",car);
        model.addAttribute("page",page);
        return "/resource/xingzheng/demo2/edit";
    }

    // administrative/updateCar
    //修改车辆信息
    @PostMapping("/administrative/updateCar")
    @ResponseBody
    public ResultVO updateCar(@Valid Car car, BindingResult bindingResult){

        //校验参数
        if(bindingResult.hasErrors()){
            String msg = bindingResult.getFieldError().getDefaultMessage();
            log.info("【车辆信息】车辆信息错误，car={},msg={}",car,msg);
            return R.error(199,msg);
        }
        carService.updateCar(car);

        return R.ok();
    }

    // 普通删除
    @PostMapping("/administrative/del")
    @ResponseBody
    public ResultVO del(Integer id){
        carService.delCar(id);
        return R.ok();
    }

    // 批量删除car
    @PostMapping("/administrative/delAll")
    @ResponseBody
    public ResultVO delAll(@RequestParam(value = "ids[]") Integer[] ids){

        carService.delAllCar(ids);

        return R.ok();
    }

    // 导出car信息
    @GetMapping("/administrative/excel")
    public void excel(Integer[] ids, HttpServletResponse response) {

        ServletOutputStream outputStream=null;
        //导出数据
        try {
        //1.查询被选中的数据信息
        List<Car> car=carService.selectCar(ids);
        //2.导出数据

            outputStream = response.getOutputStream();


        //生成随机名字
        String number = NumberUtil.getNumber(6);
        //设置导出格式
        response.setContentType("application/x-download");
        String excleName = "excle_"+number+ ".xls";
        response.addHeader("Content-Disposition", "attachment;filename=" + excleName);

        //设置表名
        ExcelUtils.createFirstRow("车辆信息",1);
        //设置内容
        ExcelUtils.createSheetValueCar(car);
        ExcelUtils.export(outputStream);
        response.getWriter().print("<script>alert('导出成功');window.history.back();</script>");
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                outputStream.flush();
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    //预定车辆信息页面
    @GetMapping("/administrative/reserveCar-ui")
    public String reserveCarUi( Model model){

        //根据id查询车辆信息
        List<Car> all = carService.findAll();
        model.addAttribute("list",all);

        return "/resource/xingzheng/demo2/yuding";
    }

    // 预定车辆
    @PostMapping("/administrative/reserveCar")
    @ResponseBody
    public ResultVO reserveCar(@Valid ReserveCar reserveCar,BindingResult bindingResult){

        //校验参数
        if(bindingResult.hasErrors()){
            String msg = bindingResult.getFieldError().getDefaultMessage();
            log.info("【车辆信息】车辆信息错误，reserveCar={},msg={}",reserveCar,msg);
            return R.error(199,msg);
        }

        /*//根据条件判断记录里是否有
        Integer count=reserveCarService.findByInfo(reserveCar);
        if (count!=0){
            return R.error(198,"");
        }*/
        //添加记录
        reserveCarService.save(reserveCar);
        return R.ok();

    }


    //会议室管理页面
    @GetMapping("/resource/xingzheng/demo1/list")
    public String meetUi(@RequestParam(defaultValue = "1") Integer page, HttpSession session, Model model){

        Integer size=3;

//        //获取存到session里面的user信息
//        User user = (User) session.getAttribute("user");
//        //根据user里的部门id获取部门信息
//        Dept dept=deptService.InfoById(user.getDeptId());
//        //根据职位id获取职位信息
//        Classsify classsify=classsifyService.InfoById(user.getClasssifyId());

        //获取全部会议室
        PageInfo<Meeting> pageInfo = meetService.findAll(page,size);

//        model.addAttribute("dept",dept);
//        model.addAttribute("classsify",classsify);
//        model.addAttribute("dated",new Date());
        model.addAttribute("pageInfo",pageInfo);
        return "resource/xingzheng/demo1/list";
    }

    //添加会议室页面
    @GetMapping("/administrative/saveMeet-ui")
    public String saveMeetUi(){
        return "resource/xingzheng/demo1/add";
    }

    //添加会议室
    @PostMapping("/administrative/saveMeet")
    @ResponseBody
    public ResultVO saveMeet(@Valid Meeting meet, BindingResult bindingResult){

        //校验参数
        if(bindingResult.hasErrors()){
            String msg = bindingResult.getFieldError().getDefaultMessage();
            log.info("【车辆信息】车辆信息错误，meet={},msg={}",meet,msg);
            return R.error(199,msg);
        }
        meetService.insertMeet(meet);

        return R.ok();
    }

    //修改会议室信息页面
    @GetMapping("/administrative/updateMeet-ui")
    public String updateMeetUi(Integer id,Integer page,Model model){

        //根据id查询车辆信息
        Meeting meeting=meetService.findById(id);
        model.addAttribute("meet",meeting);
        model.addAttribute("page",page);
        return "/resource/xingzheng/demo1/edit";
    }

    // administrative/updateCar
    //修改会议室信息
    @PostMapping("/administrative/updateMeet")
    @ResponseBody
    public ResultVO updateMeet(@Valid Meeting meeting, BindingResult bindingResult){

        //校验参数
        if(bindingResult.hasErrors()){
            String msg = bindingResult.getFieldError().getDefaultMessage();
            log.info("【会议室信息】会议室信息错误，meet={},msg={}",meeting,msg);
            return R.error(199,msg);
        }
        meetService.updateCar(meeting);

        return R.ok();
    }

    // 普通删除会议室
    @PostMapping("/administrative/delMeet")
    @ResponseBody
    public ResultVO delMeet(Integer id){
        meetService.delMeet(id);
        return R.ok();
    }

    // 批量删除会议室
    @PostMapping("/administrative/delAllMeet")
    @ResponseBody
    public ResultVO delAllMeet(@RequestParam(value = "ids[]") Integer[] ids){

        meetService.delAllMeet(ids);

        return R.ok();
    }

    // 导出会议室
    @GetMapping("/administrative/excelMeet")
    public void excelMeet(Integer[] ids, HttpServletResponse response) {

        ServletOutputStream outputStream=null;
        //导出数据
        try {
            //1.查询被选中的数据信息
            List<Meeting> meet=meetService.selectMeet(ids);
            //2.导出数据

            outputStream = response.getOutputStream();


            //生成随机名字
            String number = NumberUtil.getNumber(6);
            //设置导出格式
            response.setContentType("application/x-download");
            String excleName = "excle_"+number+ ".xls";
            response.addHeader("Content-Disposition", "attachment;filename=" + excleName);

            //设置表名
            ExcelUtils.createFirstRow("会议室信息",2);
            //设置内容
            ExcelUtils.createSheetValueMeet(meet);
            ExcelUtils.export(outputStream);
            response.getWriter().print("<script>alert('导出成功');window.history.back();</script>");
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                outputStream.flush();
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    //预定会议室页面
    @GetMapping("/administrative/ReserveMeet-ui")
    public String ReserveMeetUi(@RequestParam(defaultValue = "1") Integer page,Model model, String ids,String startTime,String endTime){


        //查询所有会议室
        Integer size=3;
        if (ids==null) {
            //获取全部会议室
            PageInfo<Meeting> pageInfo = meetService.findAll(page, size);
            model.addAttribute("pageInfo", pageInfo);
        }else {
            String[] idss=ids.split(",");
            //获取可用会议室
            PageInfo<Meeting> pageInfo = meetService.findByIds(page, size,idss);
            model.addAttribute("pageInfo", pageInfo);
            model.addAttribute("startTime",startTime);
            model.addAttribute("endTime",endTime);
            model.addAttribute("ids", ids);
        }


        //查询所有会议类型
        List<MeetType> typeList = meetTypeService.findAll();
        model.addAttribute("typeList",typeList);

        return "/resource/xingzheng/demo1/yuding";
    }

    // 查找可用会议室
    @PostMapping("/administrative/leisureId")
    @ResponseBody
    public ResultVO leisureId(@RequestParam(value = "start") String startTime, @RequestParam(value = "endTime")String endTime){

            //查询空闲的id
        List<Integer> ids=reserveMeetService.findLeisureId(startTime,endTime);

        return R.ok(ids);
    }


    //添加预定会议室的记录
    @PostMapping("/administrative/ReserveMeet")
    @ResponseBody
    public ResultVO reserveMeet( String startTime, String endTime, String realName, Integer meetId, Integer meetTypeId, Integer userId) {

        //校验参数
//        if(bindingResult.hasErrors()){
//            String msg = bindingResult.getFieldError().getDefaultMessage();
//            log.info("【会议室信息】添加预定会议室信息错误，reserveMeet={},msg={}",reserveMeet,msg);
//            return R.error(199,msg);
//        }

        ReserveMeet reserveMeet=new ReserveMeet();
        Date start=new Date(Long.parseLong(startTime));
        Date end=new Date(Long.parseLong(endTime));

        SimpleDateFormat formatter=new SimpleDateFormat("yyyy-MM-dd HH:mm");

           startTime= formatter.format(start);
           endTime= formatter.format(end);

        reserveMeet.setStartTime(start);
        reserveMeet.setEndTime(end);
        reserveMeet.setRealName(realName);
        reserveMeet.setMeetId(meetId);
        reserveMeet.setMeetTypeId(meetTypeId);
        reserveMeet.setUserId(userId);

        reserveMeetService.saveRecord(reserveMeet);

        return R.ok();
    }

    //查看预定会议室的记录
    @GetMapping("/administrative/ReserveMeetLog")
    public String reserveMeetLog(@RequestParam(defaultValue = "1") Integer page, Model model){

        Integer size=3;

        //预定会议室记录
        PageInfo<ReserveMeet> pageInfo=reserveMeetService.findAll(page,size);
        //所有会议室
        List<Meeting> meeting=meetService.findAll();
        //所有用户
        List<User> users = userService.findAll();
        //所有会议室类型
        List<MeetType> typeList = meetTypeService.findAll();


        model.addAttribute("pageInfo",pageInfo);
        model.addAttribute("meeting",meeting);
        model.addAttribute("users",users);
        model.addAttribute("typeList",typeList);


        return "resource/xingzheng/demo1/list1";
    }

    // 条件查找会议室的预定记录
    @GetMapping("/administrative/ReserveMeetLogLike")
    public String reserveMeetLogLike(HttpServletResponse response, @RequestParam(defaultValue = "1") Integer page, Model model,
                                     String startTime, String endTime, String realName, Integer meetId, Integer meetTypeId) throws IOException {

        Integer size=3;

        ReserveMeet reserveMeet=new ReserveMeet();
        reserveMeet.setRealName(realName);
        reserveMeet.setMeetId(meetId);
        reserveMeet.setMeetTypeId(meetTypeId);

        PageInfo<ReserveMeet> pageInfo=reserveMeetService.findInfoLike(page,size,reserveMeet);

        if (pageInfo.getList().isEmpty()){
            String infoNull="null";
            model.addAttribute("infoNull",infoNull);
        }

        //所有会议室
        List<Meeting> meeting=meetService.findAll();
        //所有用户
        List<User> users = userService.findAll();
        //所有会议室类型
        List<MeetType> typeList = meetTypeService.findAll();

        model.addAttribute("pageInfo",pageInfo);
        model.addAttribute("meeting",meeting);
        model.addAttribute("users",users);
        model.addAttribute("typeList",typeList);
        //g给一个条件，把like查询与普通查询分开 String realName, Integer meetId, Integer meetTypeId
        model.addAttribute("realNameT",realName);
        model.addAttribute("meetIdT",meetId);
        model.addAttribute("meetTypeIdT", meetTypeId);


        return "resource/xingzheng/demo1/list2";
    }


    // 导出会议室预定记录
    @GetMapping("/administrative/excelReserveMeet")
    public void excelReserveMeet(Integer[] ids, HttpServletResponse response) {

        ServletOutputStream outputStream=null;
        //导出数据
        try {
            //1.查询被选中的数据信息
            List<ReserveMeet> reserveMeet=reserveMeetService.selectReserveMeet(ids);
            //2.导出数据

            outputStream = response.getOutputStream();


            //生成随机名字
            String number = NumberUtil.getNumber(6);
            //设置导出格式
            response.setContentType("application/x-download");
            String excleName = "excle_"+number+ ".xls";
            response.addHeader("Content-Disposition", "attachment;filename=" + excleName);

            //设置表名
            ExcelUtils.createFirstRow("会议室预定记录",3);
            //设置内容
            ExcelUtils.createSheetValueReserveMeet(reserveMeet);
            ExcelUtils.export(outputStream);
            response.getWriter().print("<script>alert('导出成功');window.history.back();</script>");
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                outputStream.flush();
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    //行政操作成功后跳转的页面
    @GetMapping("/administrative/success")
    public String success(){

//        return "redirect:index";
        return "success";
    }

}
